package A099queue;

/**
 * SynchronousQueue没有容量。
 * <p>
 * 与其他BlockingQueue不同，SynchronousQueue是一个不存储元素的BlockingQueue。
 * <p>
 * 每一个put操作必须要等待一个take操作，否则不能继续添加元素，反之亦然。
 */

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.TimeUnit;

public class C003_SynchronousQueue_put_take_正常运行 {
    public static void main(String[] args) {
        BlockingQueue<String> blockingQueue = new SynchronousQueue<>();

        new Thread(() -> {
            try {
                blockingQueue.put("A");
                System.out.println(Thread.currentThread().getName() + "\t put A ");

                blockingQueue.put("B");
                System.out.println(Thread.currentThread().getName() + "\t put B ");

                blockingQueue.put("C");
                System.out.println(Thread.currentThread().getName() + "\t put C ");

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "t1").start();

        new Thread(() -> {
            try {

                try {
                    TimeUnit.SECONDS.sleep(5);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                String a = blockingQueue.take();
                System.out.println(Thread.currentThread().getName() + "\t take A =" + a);

                try {
                    TimeUnit.SECONDS.sleep(5);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                String b = blockingQueue.take();
                System.out.println(Thread.currentThread().getName() + "\t take B =" + b);

                try {
                    TimeUnit.SECONDS.sleep(5);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                String c = blockingQueue.take();
                System.out.println(Thread.currentThread().getName() + "\t take C =" + c);

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "t2").start();
    }

}
